﻿using GKQC.Common;
using GKQC.DbHelper.DbModels;
using GKQC.Language;
using NPOI.HSSF.UserModel;
using NPOI.SS.UserModel;
using NPOI.XSSF.UserModel;
using System;
using System.Collections.Generic;
using System.Diagnostics;
using System.IO;
using System.Linq;
using System.Reflection;
using System.Runtime.CompilerServices;
using System.Text;
using System.Windows.Forms;

namespace GKQC.Ort.Reports
{
    public class OrtReportFactory
    {
        public static IWorkbook GenOrtReport(OrtHeadModel head, ReportSetModel reportSet, string path,bool isCreateFile)
        {
            Assembly ass = null;
            Type type = null;
            try
            {
                string DllPath = "GKQC.Ort.Reports.dll";//GKQC.Ort.Reports.dll
                string typename = "GKQC.Ort.Reports." + reportSet.Code;

                try
                {
                    ass = Assembly.LoadFrom(DllPath); //利用dll的路径加载,同时将此程序集所依赖的程序集加载进来,需后辍名.dll
                                                      //Assembly.LoadFile 只加载指定文件，并不会自动加载依赖程序集.Assmbly.Load无需后辍名，加载dll后,需要使用dll中某类.
                    type = ass.GetType(typename);//利用类型的命名空间和名称获得类型需要实例化类型,才可以使用,参数可以人为的指定,也可以无参数,静态实例可以省略
                                                 //Object obj = Activator.CreateInstance(type,params[]);//利用指定的参数实例话类型，调用类型中的某个方法:
                }
                catch(Exception ex)
                {
                    Logger.LogError(ex);
                }

                if (type == null)
                {
                    System.Reflection.Assembly assembly = System.Reflection.Assembly.GetExecutingAssembly();
                    type = assembly.GetType(typename);
                }

                if(type == null)
                {
                    QMessageBox.Show("無法生成報表，因為报表代号未定義：" + reportSet.Code, "提示", MessageBoxButtons.OK, MessageBoxIcon.Warning);
                    return null;
                }

                BaseReport reportClass = (BaseReport)Activator.CreateInstance(type);
                return reportClass.GenReport(head, reportSet, path, isCreateFile);
            }
            catch (IOException ex)
            {
                Logger.LogError(ex);
                QMessageBox.Show("请确认是否打开了同名Excel文件" + "\r\n" + ex.Message, "異常S02010", MessageBoxButtons.OK, MessageBoxIcon.Error);
            }
            catch (Exception ex)
            {
                Logger.LogError(ex);
                QMessageBox.Show(ex.Message, "異常S0201", MessageBoxButtons.OK, MessageBoxIcon.Error);
            }
            finally
            {
                if(ass != null)
                    ass = null;
                if(type != null)
                    type = null;
            }

            return null;
        }

        /// <summary>
        /// 導出多個單獨的報表
        /// </summary>
        /// <param name="heads"></param>
        /// <param name="reportSets"></param>
        /// <param name="path"></param>
        /// <param name="isCreateFile"></param>
        public static void GetBatchReports(List<OrtHeadModel> heads, List<ReportSetModel> reportSets, string path, bool isCreateFile)
        {
            if (heads == null || heads.Count == 0 || reportSets == null || reportSets.Count == 0) return;

            try
            {
                for(int i=0;i<heads.Count;i++)
                {
                    try
                    {
                        var rs2 = reportSets.Where(r => r.Id == heads[i].ReportId);
                        if (rs2.Any())
                        {
                            ReportSetModel r2 = rs2.First();
                            GenOrtReport(heads[i], r2, path, true);
                        }
                    }
                    catch(Exception ex)
                    {
                        Logger.LogMessage("批量導出報表失敗：headId: " + heads[i].Id.ToString() 
                            + "; ReportId:" +heads[i].ReportId.ToString());
                        Logger.LogError(ex);
                    }
                }
            }
            catch (Exception ex)
            {
                Logger.LogMessage("批量導出報表失敗：");
                Logger.LogError(ex);
            }
        }



        /// <summary>
        /// 信赖性试验总览
        /// </summary>
        /// <param name="heads"></param>
        /// <param name="reportSets"></param>
        /// <param name="path"></param>
        /// <param name="isCreateFile"></param>
        public static void GetSumReports(List<OrtHeadModel> heads, ReportSetModel reportSet, string path, bool isCreateFile)
        {
            if (heads == null || heads.Count == 0) return;

            try
            {
                for (int i = 0; i < heads.Count; i++)
                {
                    try
                    {
                        R999 r999 = new R999();
                        r999.GenReport(heads, reportSet, path, isCreateFile);
                    }
                    catch (Exception ex)
                    {
                        Logger.LogMessage("批量導出報表失敗：headId: " + heads[i].Id.ToString()
                            + "; ReportId:" + heads[i].ReportId.ToString());
                        Logger.LogError(ex);
                    }
                }
            }
            catch (Exception ex)
            {
                Logger.LogMessage("批量導出報表失敗：");
                Logger.LogError(ex);
            }
        }


        public static IWorkbook GetAllJiscReport(List<OrtHeadModel> heads, List<ReportSetModel> reportSets, string path, bool isCreateFile)
        {
            IWorkbook workbook = new HSSFWorkbook();

            if (heads == null || heads.Count == 0 || reportSets == null || reportSets.Count == 0) return workbook;

            try
            {
                //return R000.GenAllReport(heads, reportSets, path, isCreateFile);

                Assembly ass = null;
                Type type = null;
                try
                {
                    string DllPath = "GKQC.Ort.Reports.dll";//GKQC.Ort.Reports.dll
                    string typename = "GKQC.Ort.Reports." + "R000";

                    try
                    {

                        ass = Assembly.LoadFrom(DllPath); //利用dll的路径加载,同时将此程序集所依赖的程序集加载进来,需后辍名.dll
                                                          //Assembly.LoadFile 只加载指定文件，并不会自动加载依赖程序集.Assmbly.Load无需后辍名，加载dll后,需要使用dll中某类.
                        type = ass.GetType(typename);//利用类型的命名空间和名称获得类型需要实例化类型,才可以使用,参数可以人为的指定,也可以无参数,静态实例可以省略
                                                     //Object obj = Activator.CreateInstance(type,params[]);//利用指定的参数实例话类型，调用类型中的某个方法:
                    }
                    catch(Exception ex)
                    {
                        Logger.LogError(ex);
                    }

                    if (type == null)
                    {
                        System.Reflection.Assembly assembly = System.Reflection.Assembly.GetExecutingAssembly();
                        type = assembly.GetType(typename);
                    }

                    if (type == null)
                    {
                        QMessageBox.Show("無法生成報表，因為报表代号未定義：" + "R000", "提示", MessageBoxButtons.OK, MessageBoxIcon.Warning);
                        return null;
                    }

                    //GenAllReport
                    var reportClass = Activator.CreateInstance(type);
                    MethodInfo method = type.GetMethod("GenAllReport");      // 获取方法信息
                    object[] parameters = new object[] { heads, reportSets, path, isCreateFile };
                    method.Invoke(reportClass, parameters);                           // 调用方法，参数为空
                }
                catch (IOException ex)
                {
                    Logger.LogError(ex);
                    QMessageBox.Show("请确认是否打开了同名Excel文件" + "\r\n" + ex.Message, "異常S02010", MessageBoxButtons.OK, MessageBoxIcon.Error);
                }
                catch (Exception ex)
                {
                    Logger.LogError(ex);
                    QMessageBox.Show(ex.Message, "異常S0201", MessageBoxButtons.OK, MessageBoxIcon.Error);
                }
                finally
                {
                    if (ass != null)
                        ass = null;
                    if (type != null)
                        type = null;
                }
            }
            catch (Exception ex)
            {
                Logger.LogMessage("生成其他汇总报表報表失敗：");
                Logger.LogError(ex);
            }

            return workbook;
        }

        /// <summary>
        /// 文本样式：CD Series310uF16V 16X12
        /// </summary>
        /// <param name="head"></param>
        /// <returns></returns>
        public static string GetExcelTempFileName(OrtHeadModel head, ReportSetModel reportSet)
        {
            string filename = string.Empty;
            try
            {
                if (head == null) filename = Guid.NewGuid().ToString();
                else
                {
                    filename = head.LotNo + "-" + head.Pn 
                        //+ "-" 
                        //+  (reportSet == null ? head.Id.ToString() : reportSet.Name )
                        + (head.IsBatchExport ? (" " + head.Id.ToString()) : string.Empty);
                }
                if(string.IsNullOrWhiteSpace(filename))
                    filename = head.Series + " Series"
                    + head.Cap.ToString() + "uF" + head.Voltage.ToString() + "V " + head.Size.Replace("*", "X")
                    
                    ;
            }
            catch
            {
                
            }

            if(string.IsNullOrWhiteSpace(filename)) filename = Guid.NewGuid().ToString();

            return filename;
        }

        public static List<string> ValidStringList = new List<string>(new string[] { "OK", "NG", "PASS", "FAIL" });

        /// <summary>
        /// CAP 小数位
        /// </summary>
        /// <param name="capValue"></param>
        /// <returns></returns>
        public static string GetCapNumFormat(double capValue)
        {
            string format = "0.00";
            if (capValue >= 1000)
                format = "0";
            else if (capValue >= 100)
                format = "0.0";
            else if (capValue >= 10)
                format = "0.00";
            else if (capValue < 10)
                format = "0.000";

            return format;
        }

        /// <summary>
        /// CAP 小数位
        /// </summary>
        /// <param name="capValue"></param>
        /// <returns></returns>
        public static int GetCapFormatNum(double capValue)
        {
            int format = 2;
            if (capValue >= 1000)
                format = 0;
            else if (capValue >= 100)
                format = 1;
            else if (capValue >= 10)
                format = 2;
            else if (capValue < 10)
                format = 3;


            return format;
        }

        /// <summary>
        /// LC小数位处理
        /// </summary>
        /// <param name="lcvalue"></param>
        /// <returns></returns>
        public static string GetLcNumFormat(double lcvalue)
        {
            //return GetCapNumFormat(lcvalue);
            string format = "0.00";
            if (lcvalue < 0.1)
                format = "0.000";

            return format;
        }

        /// <summary>
        /// LC小数位处理
        /// </summary>
        /// <param name="lcvalue"></param>
        /// <returns></returns>
        public static int GetLcFormatNum(double lcvalue)
        {
            //return GetCapFormatNum(lcvalue);
            int format = 2;
            if (lcvalue < 0.1)
                format = 3;

            return format;
        }
    }
}
